package com.example.weather_app.diary;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.example.weather_app.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ReminderReceiver extends BroadcastReceiver {
    private static final String TAG = "ReminderReceiver";
    private static final String CHANNEL_ID = "diary_reminder_channel";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && intent.getAction() != null) {
            Log.d(TAG, "onReceive: Received action: " + intent.getAction());

            // 打印所有额外数据，便于调试
            if (intent.getExtras() != null) {
                Log.d(TAG, "onReceive: Extras: " + intent.getExtras());
            }

            // 处理设备启动事件（来自BootReceiver）
            if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
                Log.d(TAG, "onReceive: Handling BOOT_COMPLETED action");
                handleBootCompleted(context);
            }
            // 处理日记提醒事件
            else if ("com.example.weather_app.ACTION_DIARY_REMINDER".equals(intent.getAction())) {
                Log.d(TAG, "onReceive: Handling diary reminder action");
                String diaryId = intent.getStringExtra("diaryId");
                String reminderTime = intent.getStringExtra("reminderTime");

                if (diaryId != null) {
                    Log.d(TAG, "onReceive: Showing reminder for diaryId: " + diaryId);
                    if (reminderTime != null) {
                        Log.d(TAG, "onReceive: Reminder time: " + reminderTime);
                    }
                    showReminderNotification(context, diaryId);
                } else {
                    Log.e(TAG, "onReceive: diaryId is null in reminder intent");
                }
            }
        } else {
            Log.e(TAG, "onReceive: Intent or action is null");
        }
    }

    private void handleBootCompleted(Context context) {
        Log.d(TAG, "handleBootCompleted: Restoring reminders after device boot");

        // 设备启动后恢复所有提醒
        DiaryDao diaryDao = new DiaryDao(context);
        List<Diary> reminderDiaries = diaryDao.getReminderDiaries();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        long currentTime = System.currentTimeMillis();

        Log.d(TAG, "handleBootCompleted: Found " + reminderDiaries.size() + " reminder diaries");

        for (Diary diary : reminderDiaries) {
            String reminderTime = diary.getReminderTime();
            if (reminderTime == null) {
                Log.w(TAG, "handleBootCompleted: Reminder time is null for diaryId: " + diary.getId());
                continue;
            }

            try {
                Date reminderDate = dateFormat.parse(reminderTime);
                long triggerTime = reminderDate.getTime();

                // 只恢复未来的提醒
                if (triggerTime > currentTime) {
                    Log.d(TAG, "handleBootCompleted: Restoring reminder for diaryId: " + diary.getId() +
                            ", time: " + new Date(triggerTime));
                    setReminder(context, diary.getId(), triggerTime);
                } else {
                    Log.w(TAG, "handleBootCompleted: Ignoring past reminder for diaryId: " + diary.getId() +
                            ", time: " + new Date(triggerTime));

                    // 可以选择删除过期的提醒
                    diary.setReminderTime(null);
                    diaryDao.updateDiary(diary);
                }
            } catch (ParseException e) {
                Log.e(TAG, "handleBootCompleted: Error parsing time: " + reminderTime +
                        " for diaryId: " + diary.getId(), e);
            }
        }
    }

    private void setReminder(Context context, String diaryId, long triggerTime) {
        Log.d(TAG, "setReminder: Setting reminder for diaryId: " + diaryId +
                ", trigger time: " + new Date(triggerTime));

        // 检查触发时间是否合理
        long currentTime = System.currentTimeMillis();
        if (triggerTime < currentTime) {
            Log.e(TAG, "setReminder: Trigger time is in the past! " +
                    "current: " + new Date(currentTime) +
                    ", trigger: " + new Date(triggerTime));
            return;
        }

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, ReminderReceiver.class);
        intent.setAction("com.example.weather_app.ACTION_DIARY_REMINDER");
        intent.putExtra("diaryId", diaryId);

        // 添加提醒时间作为额外参数，便于调试
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        intent.putExtra("reminderTime", sdf.format(new Date(triggerTime)));

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context,
                diaryId.hashCode(),
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );

        // 检查精确闹钟权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (alarmManager.canScheduleExactAlarms()) {
                Log.d(TAG, "setReminder: Has exact alarm permission, API: " + Build.VERSION.SDK_INT);
                setExactAlarm(alarmManager, triggerTime, pendingIntent);
            } else {
                Log.e(TAG, "setReminder: No exact alarm permission on API " + Build.VERSION.SDK_INT +
                        ". Reminder may not trigger accurately.");
                setExactAlarm(alarmManager, triggerTime, pendingIntent); // 即使没有权限也尝试设置
            }
        } else {
            Log.d(TAG, "setReminder: Exact alarm permission not required on API " + Build.VERSION.SDK_INT);
            setExactAlarm(alarmManager, triggerTime, pendingIntent);
        }
    }

    private void setExactAlarm(AlarmManager alarmManager, long triggerTime, PendingIntent pendingIntent) {
        long currentTime = System.currentTimeMillis();
        long timeDiff = triggerTime - currentTime;

        Log.d(TAG, "setExactAlarm: Setting alarm for " + new Date(triggerTime) +
                " (in " + timeDiff + "ms)");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Log.d(TAG, "setExactAlarm: Using setExactAndAllowWhileIdle for API " + Build.VERSION.SDK_INT);
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Log.d(TAG, "setExactAlarm: Using setExact for API " + Build.VERSION.SDK_INT);
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
        } else {
            Log.d(TAG, "setExactAlarm: Using set for API " + Build.VERSION.SDK_INT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
        }
    }

    private void showReminderNotification(Context context, String diaryId) {
        Log.d(TAG, "showReminderNotification: Showing notification for diaryId: " + diaryId);

        DiaryDao dao = new DiaryDao(context);
        Diary diary = dao.getDiaryById(diaryId);

        if (diary != null) {
            Log.d(TAG, "showReminderNotification: Found diary: " + diary.getTitle());

            NotificationManager notificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            Intent notificationIntent = new Intent(context, DiaryDetailActivity.class);
            notificationIntent.putExtra("diaryId", diaryId);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

            PendingIntent contentIntent = PendingIntent.getActivity(
                    context,
                    diaryId.hashCode(),
                    notificationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
            );

            // 构建通知
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_reminder)
                    .setContentTitle("日记提醒")
                    .setContentText(diary.getTitle())
                    .setContentIntent(contentIntent)
                    .setAutoCancel(true)
                    .setPriority(NotificationCompat.PRIORITY_HIGH);

            // Android 8.0+ 需要创建通知渠道
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Log.d(TAG, "showReminderNotification: Creating notification channel for API " + Build.VERSION.SDK_INT);

                CharSequence name = "日记提醒";
                String description = "日记应用的提醒通知";
                int importance = NotificationManager.IMPORTANCE_HIGH;
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
                channel.setDescription(description);
                notificationManager.createNotificationChannel(channel);
            }

            notificationManager.notify(diaryId.hashCode(), builder.build());
            Log.d(TAG, "showReminderNotification: Notification shown for diaryId: " + diaryId);
        } else {
            Log.e(TAG, "showReminderNotification: Diary not found for diaryId: " + diaryId);
        }
    }
}